<script setup lang="ts">
import MarkdownIt from 'markdown-it'
import '@/public/css/markdown.min.css'
import hljs from 'highlight.js'
import 'highlight.js/styles/a11y-light.css';
import markdownItTextualUml from 'markdown-it-textual-uml/src/index'
import mermaid from 'mermaid';

const props = defineProps({
  name: String
});
const sourceContent = ref('');
const mdi = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlightAuto: true,
  highlightLines: true,
  xhtmlOut:     false,
  // Convert '\n' in paragraphs into <br>
  breaks:       false,
  langPrefix:   'language-',
  quotes: '^',
  highlight: (str: string, lang: string) => {
    if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(str, { language: lang }).value;
      } catch (__) {}
    }
    return ''; // use external default escaping
  }
}).use(markdownItTextualUml);

const queryDoc = async () => {
  mermaid.initialize({ startOnLoad: false, theme: 'forest' });
  const response = await $fetch(`/api/getMd`, {
    query: {name: props.name}
  });
  sourceContent.value = response as string;
};
watch(props, async () => {
  await queryDoc();
}, {immediate: true, deep: true})

const markdownContent = ref('');
watch(sourceContent, async () => {
  markdownContent.value = await mdi.render(sourceContent.value);
  await nextTick(() => {
    mermaid.run();
  });
});
let timer: any = null;
const clearTime = () => {
  clearTimeout(timer);
  timer = null;
};
const changeFn = () => {
  if (timer) {
    clearTime();
  }
  timer = setTimeout(() => {
    $fetch('/api/editMd', {
      method: 'get',
      query: {
        name: props.name,
        content: sourceContent.value
      }
    });
  }, 2000);
};
onUnmounted(() => {
  clearTime();
});

const editSteps = [{
  name: '全屏编辑',
  icon: 'material-symbols:contract-edit-sharp'
},{
  name: '分屏编辑',
  icon: 'bi:layout-split'
},{
  name: '预览',
  icon: 'material-symbols:preview'
}];
const editStep = ref(2);
function indent(event) {
  const { value } = event.target;
  const start = event.target.selectionStart;
  const end = event.target.selectionEnd;
  const before = value.substring(0, start);
  const after = value.substring(end);
  const selected = value.substring(start, end);
  const indentString = '  '; // 使用两个空格作为缩进
  const newSelected = selected.split('\n').map(line => indentString + line).join('\n');
  sourceContent.value = before + newSelected + after;
  event.target.selectionStart = start;
  event.target.selectionEnd = end + (newSelected.length - selected.length);
}
</script>

<template>
  <div class="min-h-[100vh] relative flex flex-col flex-auto bg-gray-100/95">
    <div class="flex items-center p-2 bg-gray-300/95">
      <h1 class="text-lg m-0 pl-2 flex-1">{{ props.name }}</h1>
      <div class="flex gap-2">
        <button v-for="(item, key) in editSteps" :key="key" :class="[editStep === key ? 'bg-gray-700 text-white' : 'bg-gray-100 text-gray-700']" :name="item.name" class="bg-gray-100 hover:bg-gray-700 hover:text-white font-bold py-2 px-4 rounded cursor-pointer" @click="editStep=key"><Icon :name="item.icon" size="20" /></button>
      </div>
    </div>
    <div :class="{'container': editStep !== 1}" class="mx-auto flex-auto box-border relative w-full">
      <div class="flex items-stretch absolute inset-0 overflow-hidden">
        <div class="relative bg-red-200 flex-auto" :class="{hidden: editStep === 2}">
          <div class="resize-x overflow-x-scroll w-[500px] h-full resize-bar cursor-ew-resize opacity-0"></div>
          <div class="resize-line relative pointer-events-none"></div>
          <div class="absolute inset-0 mr-2"><textarea v-model="sourceContent" class="absolute inset-0 resize-none p-4 bg-none" @change="changeFn" @keydown.tab.prevent="indent" /></div>
        </div>
        <div class="relative min-w-0 p-4 flex-auto h-full overflow-auto" :class="{hidden: editStep === 0}">
          <div v-html="markdownContent" class="markdown-body"></div>
        </div>
      </div>
    </div>
  </div>
</template>
<style scoped>
/* 拖拽线 */
.resize-line {
  position: absolute;
  right: 0; top: 0; bottom: 0;
  border-left: 8px dashed skyblue;
  pointer-events: none;
}
.resize-bar:hover ~ .resize-line,
.resize-bar:active ~ .resize-line {
  border-left: 8px dashed skyblue;
}
.resize-bar::-webkit-scrollbar {
  width: 8px;
  background: blue;
  height: 100vh;
  opacity: 0;
}

/* Firefox只有下面一小块区域可以拉伸 */
@supports (-moz-user-select: none) {
  .resize-bar:hover ~ .resize-line,
  .resize-bar:active ~ .resize-line {
    border-left: 1px solid #bbb;
  }
  .resize-bar:hover ~ .resize-line::after,
  .resize-bar:active ~ .resize-line::after {
    content: '';
    position: absolute;
    width: 16px; height: 16px;
    bottom: 0; right: -8px;
    background-size: 100% 100%;
  }
}
</style>